#include "chatwidget.h"
#include "ui_chatwidget.h"
#include "mainwidget.h"

#include <QTime>
#include <QFileDialog>
#include <QStringList>
#include <QDebug>

ChatWidget::ChatWidget(const QString &uuid) :
    QWidget(),
    ui(new Ui::ChatWidget),
    m_uuid(uuid)
{
    ui->setupUi(this);

    connect(ui->btnSendMessage, &QPushButton::clicked, this, &ChatWidget::onBtnSendMessage);
    connect(ui->btnSendFile, &QPushButton::clicked, this, &ChatWidget::onBtnSendFile);
    connect(ui->btnSendImage, &QPushButton::clicked, this, &ChatWidget::onBtnSendImage);
}

void ChatWidget::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    //发射关闭信号，由mainWidget(主窗口做后续处理)
    emit redayClose(m_uuid);
}

ChatWidget::~ChatWidget()
{
    delete ui;
}

void ChatWidget::addNewMessage(const QString &message)
{
    ui->editRecvMessage->append(QString("%1    %2:\n%3")
                                         .arg(this->windowTitle())
                                         .arg(QTime::currentTime().toString())
                                .arg(message));
}

void ChatWidget::addNewMessage(const QImage &image)
{
    ui->editRecvMessage->append(QString("%1    %2:\n")
                                         .arg(this->windowTitle())
                                         .arg(QTime::currentTime().toString()));
    ui->editRecvMessage->textCursor().insertImage(image);
}

void ChatWidget::addHistoryMessage(const QStringList &messageList)
{
    foreach (QString str, messageList) {
        ui->editRecvMessage->append(str);
    }
}

void ChatWidget::onBtnSendMessage()
{
    QString message = ui->editSendMessage->toPlainText();
    if(message.isEmpty()) return;
    ui->editSendMessage->clear();
    ui->editRecvMessage->append(QString("我    %1:\n%2")
                                         .arg(QTime::currentTime().toString())
                                         .arg(message));

   emit sendMessage(m_uuid, message);
}

void ChatWidget::onBtnSendFile()
{
    QString fileName = QFileDialog::getOpenFileName(this, QString("请选择你要发送的文件"));
    if(!fileName.isEmpty()){
        emit sendFile(m_uuid, fileName);
    }
}

void ChatWidget::onBtnSendImage()
{
    QString imageName = QFileDialog::getOpenFileName(this, QString("请选择你要发送的图片")
                                                     ,QString(), "*.jpg; *.png");
    if(!imageName.isEmpty()){
        //把图片插入聊天信息窗口中
        QImage image(imageName);
        ui->editRecvMessage->append(QString("我    %1:\n")
                                             .arg(QTime::currentTime().toString()));
        ui->editRecvMessage->textCursor().insertImage(image);
        //发射信号
        emit sendImage(m_uuid, imageName);
    }
}


